package com.ace.lab.starter.config;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableConfigurationProperties({ZookeeperProperties.class})
public class ZookeeperConfiguration {

    @Autowired
    private ZookeeperProperties zkConfig;

    @Bean(destroyMethod = "close")
    @ConditionalOnMissingBean
    public CuratorFramework curatorFramework() {
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .retryPolicy(new ExponentialBackoffRetry(this.zkConfig.getBaseSleepTimeMs(), this.zkConfig.getMaxRetries()))
                .connectString(this.zkConfig.getConnections())
                .connectionTimeoutMs(this.zkConfig.getConnectionTimeoutMs())
                .sessionTimeoutMs(this.zkConfig.getSessionTimeoutMs())
                .build();
        client.start();
        return client;
    }

}
